<?php


namespace Drupal\shushengyuan\Schemas;

use Drupal\shusy_sweepstake\Entity\ShusySweepstakeLog;
use Drupal\shusy_sweepstake_bind_card\Entity\ShusySweepstakeBindCard;
use Drupal\shusy_sweepstake_bind_order\Entity\ShusySweepstakeBindOrder;

/**
 * @OA\Schema(
 *   schema="SweepstakeLog",
 *   type="object",
 *   description="SweepstakeLog"
 * )
 */
class SweepstakeLog extends AbstractBaseModel {

  protected function getEntityType() {
    return 'shusy_sweepstake_log';
  }

  protected function setValue() {
    if ($this->entity instanceof ShusySweepstakeLog) {
      $value = [
        /**
         * @OA\Property(
         *   property="item",
         *   ref="#/components/schemas/SweepstakeItem",
         *   description="抽中的奖品",
         * ),
         */
        'item' => SweepstakeItem::init($this->entity->sweepstake_item_id),
        /**
         * @OA\Property(
         *   property="created",
         *   type="string",
         *   description="抽奖时间",
         * ),
         */
        'created' => $this->formatDate($this->entity->created, 'Y-m-d H:i'),

        'order' => $this->getOrder($this->entity),
        'card' => $this->getCard($this->entity),

      ];
      $this->merge($value);
    }
  }

  protected function getOrder(ShusySweepstakeLog $log) {
    $binds = shusy_sweepstake_bind_order_load_multiple(FALSE, [
      'sweepstake_log_id' => $log->id,
    ]);
    if (!empty($binds)) {
      $bind = reset($binds);
      if ($bind instanceof ShusySweepstakeBindOrder) {
        return PointExchangeOrder::init($bind->point_product_order_id);
      }
    }
    return FALSE;
  }

  protected function getCard(ShusySweepstakeLog $log) {
    $binds = shusy_sweepstake_bind_card_load_multiple(FALSE, [
      'sweepstake_log_id' => $log->id,
    ]);
    if (!empty($binds)) {
      $bind = reset($binds);
      if ($bind instanceof ShusySweepstakeBindCard) {
        return MyGiftCard::init($bind->gift_card_id);
      }
    }
    return FALSE;
  }

}
